package com.jf.game

import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.activity.viewModels
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.R
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.app.model.AppCache
import com.helloandroid.base.BaseActivity
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.GUtils
import com.helloandroid.tools.MyLog
import com.helloandroid.view.IMovingTextDataSource
import com.helloandroid.view.MovingText
import com.helloandroid.view.MySpannableString
import dai.android.util.AndroidUtils
import dai.common.util.CommonUtils

class JfGame : BaseActivity() {

    lateinit var tvRest: TextView  // 剩余次数

    lateinit var tvFu: TextView
    lateinit var tvLu: TextView
    lateinit var tvShou: TextView
    lateinit var tvCai: TextView
    lateinit var tvXi: TextView
    lateinit var ivFu: ImageView
    lateinit var ivLu: ImageView
    lateinit var ivShou: ImageView
    lateinit var ivCai: ImageView
    lateinit var ivXi: ImageView
    lateinit var tvDesc2: TextView
    lateinit var movingText: MovingText

    // contents
    val lstContent = ArrayList<RelativeLayout>()

    lateinit var hlItem: RelativeLayout

    val model: JFViewModel by viewModels()
    var isReady = false

    var mInfo: JFInfo? = null
    var curStepIdx = 0  // 当前步数索引
    var targetStepCount = 0 // 目标步数
    var elapsedCount = 0  // 走过的步数

    // 结果
    var mJFResult: JFResult? = null

    var firstDrawListener: ViewTreeObserver.OnGlobalLayoutListener? = null

    // 是否给与了视频奖励
    var hasVideoAward = false

    // 是否已经resume了
    var hasResumed = false

    override fun getContentViewResId(): Int = R.layout.activity_jf

    override fun initView() {

        // init views
        tvRest = findViewById(R.id.tvRest)
        tvFu = findViewById(R.id.tvFu)
        tvLu = findViewById(R.id.tvLu)
        tvShou = findViewById(R.id.tvShou)
        tvCai = findViewById(R.id.tvCai)
        tvXi = findViewById(R.id.tvXi)
        ivFu = findViewById(R.id.ivFu)
        ivLu = findViewById(R.id.ivLu)
        ivShou = findViewById(R.id.ivShou)
        ivCai = findViewById(R.id.ivCai)
        ivXi = findViewById(R.id.ivXi)
        hlItem = findViewById(R.id.hlItem)
        tvDesc2 = findViewById(R.id.tvDesc2)
        movingText = findViewById(R.id.movingText)
        movingText.dataSource = IMovingTextDataSource {
            val ranIdx = CommonUtils.randomInt(0, AppCache.FkNames.size - 1)
            val name = AppCache.FkNames[ranIdx]
            "恭喜玩家 $name 成功兑换100元现金}"
        }
        findBtn(R.id.ivHelp).setOnClickListener { showHelpDialog() }

        // contents
        val content1 = findViewById<RelativeLayout>(R.id.content1)
        val content2 = findViewById<RelativeLayout>(R.id.content2)
        val content3 = findViewById<RelativeLayout>(R.id.content3)
        val content4 = findViewById<RelativeLayout>(R.id.content4)
        val content5 = findViewById<RelativeLayout>(R.id.content5)
        val content6 = findViewById<RelativeLayout>(R.id.content6)
        val content7 = findViewById<RelativeLayout>(R.id.content7)
        val content8 = findViewById<RelativeLayout>(R.id.content8)
        lstContent.add(content1)
        lstContent.add(content2)
        lstContent.add(content3)
        lstContent.add(content4)
        lstContent.add(content5)
        lstContent.add(content6)
        lstContent.add(content7)
        lstContent.add(content8)

        findBtn(R.id.btnBack).setOnClickListener {
            finish()
        }

        // 开始
        findBtn(R.id.btnPlay).setOnClickListener { btnPlayClicked() }

        // 更新第一个位置
        firstDrawListener = ViewTreeObserver.OnGlobalLayoutListener {
            val content1 = lstContent[0]
            hlItem.x = content1.x
            hlItem.y = content1.y
            content1.viewTreeObserver.removeOnGlobalLayoutListener(firstDrawListener)
            firstDrawListener = null
        }
        content1.viewTreeObserver.addOnGlobalLayoutListener(firstDrawListener)

        //-------------

        tvDesc2.text = MySpannableString(this, "集齐5个福,兑换100元现金")
                .first("100")
                .textColor(R.color.red)
    }

    override fun initData() {
        model.getInfo { success, jfInfo ->
            isReady = success
            if (isReady) {
                mInfo = jfInfo
                updateUI()
            } else {
                AppUtil.toast("获取数据失败!")
            }
        }
    }

    private fun updateUI() {
        val info = mInfo!!
        updateItem(ivFu, tvFu, info.fu, R.drawable.jf_fu, R.drawable.jf_fu_fade)
        updateItem(ivLu, tvLu, info.lu, R.drawable.jf_lu, R.drawable.jf_lu_fade)
        updateItem(ivShou, tvShou, info.shou, R.drawable.jf_shou, R.drawable.jf_shou_fade)
        updateItem(ivCai, tvCai, info.cai, R.drawable.jf_cai, R.drawable.jf_cai_fade)
        updateItem(ivXi, tvXi, info.xi, R.drawable.jf_xi, R.drawable.jf_xi_fade)

        if (info.restcount > 8) {
            tvRest.text = "免费${info.restcount - 8}次"
        } else {
            if (info.restcount > 0) {
                tvRest.text = "剩余${info.restcount}次"
            } else {
                tvRest.text = "次数已用完"
            }
        }
    }

    private fun updateItem(iv: ImageView,
                           tv: TextView,
                           count: Int,
                           imgActiveRes: Int,
                           imgFadeRes: Int) {
        if (count > 0) {
            iv.setBackgroundResource(imgActiveRes)
            tv.visibility = View.VISIBLE
            tv.text = "${count}"
        } else {
            iv.setBackgroundResource(imgFadeRes)
            tv.visibility = View.INVISIBLE
        }
    }

    private fun btnPlayClicked() {
        if (!isReady) {
            AppUtil.toast("数据还未加载成功!")
            return
        }
        val info = mInfo!!
        if (info.restcount < 1) {
            AppUtil.toast("您今日次数用完!")
            return
        }

        if (model.rolling) {
            MyLog.info("正在rolling...")
            return
        }

        if (!AndroidUtils.networkConnected(AppUtil.app)) {
            AppUtil.toast("请打开网络!")
            return
        }

        if (info.restcount > 8) {
            // 免费玩
            Analyse.report(AnalyseKey.JF_FreeRoll)
            startRoll()
        } else {
            // 方便测试
            if (!AppConfig.AdToggle && AppConfig.isDebug) {
               startRoll()
            }else{
                // 视频
                VideoAdUtil.playVideoAd(this) { success ->
                    if (success) {
                        Analyse.report(AnalyseKey.JF_VideoRoll)
                        hasVideoAward = true
                    } else {
                        AppUtil.toast("视频还未准备好.")
                    }
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        hasResumed = false
    }

    override fun onResume() {
        super.onResume()
        hasResumed = true
        if (hasVideoAward) {
            hasVideoAward = true
            startRoll()
        }
    }

    private fun startRoll() {
        val info = mInfo!!
        info.restcount--

        // 计算出一个结果
        val jfResult = calResult()
        mJFResult = jfResult

        // 走到哪
        var step = when (jfResult.result_id) {
            JFViewModel.Fu -> 0
            JFViewModel.Lu -> 1
            JFViewModel.Shou -> 2
            JFViewModel.Xi -> 4
            JFViewModel.Cai -> 6
            else -> when (jfResult.count) {
                JFViewModel.BigCoin -> 5
                JFViewModel.MidCoin -> 3
                else -> 7
            }
        }

        step += 24

        //  当前是第几步
        targetStepCount = step - curStepIdx
        elapsedCount = 0
        model.roll(::rollUpdate, ::rollEnd)

        // 更新本地信息并且发送消息
        info.increase(jfResult)
        AppUtil.appViewModel().jfRoll(jfResult)
    }

    private fun rollUpdate(): Boolean {
        if (!hasResumed) {
            return false
        }
        elapsedCount++
        curStepIdx = (curStepIdx + 1) % 8
        hlItem.x = lstContent[curStepIdx].x
        hlItem.y = lstContent[curStepIdx].y
        return elapsedCount >= targetStepCount
    }

    private fun rollEnd() {
        // 显示结果对话框
        // 更新下面符信息
        updateUI()

        JFAwardDialog(this).show(supportFragmentManager)
    }

    private fun calResult(): JFResult {
        val info = mInfo!!
        if (info.kaCount() < 1) {
            // 新用户, 直接奖励一张卡
            return JFResult(model.randomKaType(), 1)
        }

        val kaTypeCount = info.kaTypeCount()
        if (kaTypeCount >= 4) {
            // 产生金币
            val type = JFViewModel.Coin
            return JFResult(type, genCoinCount())
        }

        if (kaTypeCount >= 3) {
            // 第4种福卡出现概率为 0.5%
            val n = CommonUtils.randomInt(0, 199)
            val type = when {
                n == 199 -> info.genFourthKaType()
                n >= 190 -> info.genNotKeyKaType()
                else -> JFViewModel.Coin
            }
            if (type == JFViewModel.Coin) {
                return JFResult(type, genCoinCount())
            } else {
                return JFResult(type, 1)
            }
        }

        //按既定概率产生
        val n = CommonUtils.randomInt(0, 99)
        val type = when {
            n >= 94 -> JFViewModel.Lu
            n == 93 -> JFViewModel.Fu
            n == 92 -> JFViewModel.Shou
            n == 91 -> JFViewModel.Xi
            n == 90 -> JFViewModel.Cai
            else -> JFViewModel.Coin
        }
        if (type == JFViewModel.Coin) {
            return JFResult(type, genCoinCount())
        } else {
            return JFResult(type, 1)
        }
    }

    private fun genCoinCount(): Int {
        val n = CommonUtils.randomInt(0, 89);
        return when {
            n < 20 -> JFViewModel.BigCoin
            n < 50 -> JFViewModel.MidCoin
            else -> JFViewModel.SmallCoin
        }
    }

    private fun showHelpDialog() {
        HelpDialog().show(supportFragmentManager)
    }
}